package com.itheima.youdianda.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.youdianda.common.BaseContext;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.exception.CommonException;
import com.itheima.youdianda.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
/*
@WebFilter(filterName = "webAppFilter", urlPatterns = "/*")
*/
public class WebAppFilter implements Filter {
    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();

        log.info("当前路径：{}", requestURI);
        String[] urls = new String[]{
                "/index/login",
                "/index/logout",
                "/index/reg",
                "/index/getConfig",
                "/index/profile"/*,
                "/index/getConfig",
                "/index/profile"*/
        };

        for (String url : urls) {
            if (antPathMatcher.match(url, requestURI)){
                filterChain.doFilter(request, response);
                return;
            }
        }
        //todo:
//        String token = request.getHeader("x-token");
//        if (token == null){
//            throw new CommonException("用户未登录");
//        }
//
//        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
//        int verifyToken = AppJwtUtil.verifyToken(claimsBody);
//        if (verifyToken == 1 || verifyToken == 2){
//            throw new CommonException("用户信息已失效");
//        }
//
//        assert claimsBody != null;
//        String id = (String) claimsBody.get("token");
//        log.info("当前用户id：{}", id);
//        BaseContext.setId(id);


//        Object id = request.getSession().getAttribute("id");
        String id = BaseContext.getId();
        if (id != null){
            BaseContext.setId(id.toString());
            filterChain.doFilter(request, response);
            return;
        }

        Object userId = request.getSession().getAttribute("userId");
//        String id = BaseContext.getId();
        if (userId != null){
            BaseContext.setId(userId.toString());
            filterChain.doFilter(request, response);
            return;
        }

        log.info("拦截到路径：{}", requestURI);
        response.getWriter().write(JSON.toJSONString(R.error("Not login")));
    }
}
